<?php
declare (strict_types=1);

namespace app\middleware;

use app\common\tools\ApiMemberInfo;
use app\common\tools\ApiRequestInfo;
use think\facade\Db;
use \Firebase\JWT\JWT;

class ApiMember
{
    private static $instance;
    public $member;

    public function handle($request, \Closure $next)
    {
        $token = $request->header('token');

        // 已设置过token 采用token 认证
        if(isset($token)){
            $token = trim($token);
            if (strpos($token, 'Bearer') === 0)
                $token = trim(substr($token, 6));
            if (!$token)
                return json(['status'=>0,'msg'=>'请登录后再操作']);

            [$status,$arr] = $this->checktoken($token);


            // 判断token是否验证通过
            if ($status == 0) {
                return json(['status'=>0,'msg'=>'登录失败']);
            }

            $users = Db::table('xs_user')->where('id',$arr['data']->user_id)->find();
        } else {
            $users = [];
        }

        $request->users = $users;

        return $next($request);
    }


    /**
     * token 认证
     * @return [type] [description]
     */
    public function checktoken($token)
    {
        $status = 1;
        $arr = [];
        try{
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, 'xiongshi', array('HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
                $status = 0;
            }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
                $status = 0;
            }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
                $status = 0;
        }catch(Exception $e) {  //其他错误
            $status = 0;
        }

        return [$status,$arr];
    }
}
